<?php

require_once("ReverseProxy.php"); //class for reverse proxy server
require_once("MantisAuthorize.php"); //class for authentication related

$publicBaseURL = "http://".$_SERVER['SERVER_NAME']; //the URL user's see for Google Refine
$issueTrackerBaseURL = "Your Mantis URL here"; //base URL of the Mantis Issue Tracker


$sessionID = session_id();
if ($sessionID == ""){
    session_start();
    $sessionID = session_id();
}

$auth = new MantisAuthorize;
$auth->sessionID = $sessionID;
$auth->publicBaseURL =  $publicBaseURL;
$authorizedSession = $auth->checkAuthorization();
$editIssueResolved = $auth->editIssueResolved;
$editIssue = $auth->editIssue;
if(!$editIssueResolved){
    unset($auth); //a little memory saving
}

if(!stristr($_SERVER["REQUEST_URI"], "login-check") && $authorizedSession && !$editIssueResolved){
    //OK the user is OK to use Google Refine!
    $proxy = new PhpReverseProxy();
    $proxy->getOutsideHeaders();
    $proxy->publicBaseURL =  $publicBaseURL;
    $proxy->port="";
    $proxy->host="";
    $proxy->forward_path="127.0.0.1:3333"; //default for Google Refne
    $proxy->connect();
    $proxy->output();
    unset($proxy);
}
elseif(stristr($_SERVER["REQUEST_URI"], "login-check-ok")){
    
    // handle POST requests giving authorization OK from Mantis
    
    $auth = new MantisAuthorize;
    $auth->checkMessage();

    $message = array("authorized" => $auth->authorization,
                     "sessionID" => $auth->sessionID,
                     "savedAuth" => $auth->savedAuth);
    $output = json_encode($message, 1);
    
    header('Content-Type: application/json; charset=utf8');
    echo $output;
}
elseif(stristr($_SERVER["REQUEST_URI"], "login-check-project")){

    $auth = new MantisAuthorize;
    $auth->projectUsers(); //display project user IDs if authorized
}
elseif(stristr($_SERVER["REQUEST_URI"], "login-check-edit-issue")){

    $auth = new MantisAuthorize;
    $auth->updateProjectEditIssueState(); //update the state of the edit issue (editIssueResolved is TRUE or FALSE)
}
elseif($editIssueResolved){
    //Editing the dataset is CLOSED / RESOLVED (according to Mantis), show notification to the user
    require_once("pageParts.php");
    echo displayPageTop("Dataset Editing Closed", false);
    echo displayEditIssue($editIssue);
    echo displayPageBottom();

}
else{
    //Show user the Login screen
    require_once("pageParts.php");
    echo displayPageTop("Login to Google Refine");
    echo displayLoginPage();
    echo displayPageBottom();
}

?>